import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Image, TextInput, Dimensions, ToastAndroid, ScrollView, Platform } from "react-native";
import navigationSeevice from '../../../../../../components/navigation/navigationSeevice';
import { Common } from '../../../../../../component/common/Common';
import { RangTime } from '../../../../../../component/common/RangTime';
import { API, API_GENERATE } from '../../../../../../config/api';
import ToastUtil from '../../../../../../utils/toast';
import HTTP from '../../../../../../utils/http';
import Upload from '../../../../../../utils/Upload';
import Dictionary from '../../../../../../utils/dictionary';
import { STORAGE_CONSTANT } from '../../../../../../config/storage';
import { CommonData } from '../_common/common.js';
import moment from 'moment';
var ImagePicker = require('react-native-image-picker');
const ScreenWidth = Dimensions.get('window').width;
const ScreenHeight = Dimensions.get('window').height;
const scale = ScreenWidth / 375;
let defaultImg = require('../../../../../../imgs/addphoto.png');
let close = require('../../../../../../imgs/delete.png');
let selectIcon = require('../../../../../../imgs/select.png');
let addressIcon = require('../../../../../../imgs/address.png');
let dateIcon = require('../../../../../../imgs/time.png');

var imgOptions = {
  title: '请选择图片来源',
  cancelButtonTitle: '取消',
  takePhotoButtonTitle: '拍照',
  chooseFromLibraryButtonTitle: '相册图片',
  quality: 0.1,
  storageOptions: {
    skipBackup: true,
    path: 'images'
  }
};

var source = null;

export class CreateMaintenance extends Component {
  static navigationOptions = {
    header: null
  }

  constructor(props) {
    super(props);
    this.state = {
      imgServer: [],
      attachmentId: [],
      imgUrl: '',
      showTimeModal: false,
      modalObj: {
        currSelectIndex: -1,
        currTitle: '',
        currlistData: [],
        currCb: null,
        currIsVisible: false,
      },
      mainTypeSelect: '',
      mainTypeText: '请选择维护类型',
      mainMethodSelect: '',
      mainMethodText: '请选择维护方式',
      mainObjectSelect: '',
      mainObjectText: '请选择维护对象',
    };
    this.CommonData = {
      mainType: [
      ],
      methodType: [
      ],
    }
    this.params = {};
    this.dateObj = {
      beginDate: CommonData._format('date1', moment().subtract(1, 'months').calendar()),
      endDate: CommonData._format('date1', moment())
    };
    this._uploadImg = this._uploadImg.bind(this);
    this._changeImg = this._changeImg.bind(this);
  }

  async componentWillMount() {
    await this._init();
  }

  //初始数据处理
  _init = async () => {
    const { data } = this.props;
    const { companyInfoVO, contactorList } = data || {};
    this.params.companyId = companyInfoVO.companyId;
    this.objectType = [];
    contactorList && contactorList.length && contactorList.map((item, index) => {
      this.objectType.push({ dictName: item.contactorName, dictKey: item.contactorId, mobileNo: item.mobileNo })
    })
    this.CommonData.mainType = await Dictionary.get('COMPANY_ADD_VISIT_TYPE');
    this.CommonData.methodType = await Dictionary.get('COMPANY_ADD_VISIT_METHOD')
  }

  selectMain = (type) => {
    switch (type) {
      case 'type':
        this.openModal('请选择维护类型', this.CommonData.mainType, this.state.mainTypeSelect, this.getMainType)
        break;
      case 'method':
        this.openModal('请选择维护方式', this.CommonData.methodType, this.state.mainMethodSelect, this.getMethodType)
        break;
      case 'object':
        this.openModal('请选择维护对象', this.objectType, this.state.mainObjectSelect, this.getMethodObject)
        break;
      default:
        break;
    }
  }

  getMainType = (index) => {
    this.params.visitType = this.CommonData.mainType[index].dictKey;
    this.setState({
      mainTypeSelect: index,
      mainTypeText: this.CommonData.mainType[index].dictName
    })
    this.closeModal();
  }

  getMethodType = (index) => {
    this.params.visitMethod = this.CommonData.methodType[index].dictKey;
    this.setState({
      mainMethodSelect: index,
      mainMethodText: this.CommonData.methodType[index].dictName
    })
    this.closeModal();
  }

  getMethodObject = (index) => {
    this.params.contactorName = this.objectType[index].dictName;
    this.params.contactorId = this.objectType[index].dictKey;
    this.params.mobileNo = this.objectType[index].mobileNo;
    this.setState({
      mainObjectSelect: index,
      mainObjectText: this.objectType[index].dictName
    })
    this.closeModal();
  }

  openModal(title, listData, index, cb) {
    let { modalObj } = this.state;
    modalObj.currIsVisible = true;
    modalObj.currTitle = title;
    modalObj.currlistData = listData;
    modalObj.currSelectIndex = index;
    modalObj.currCb = cb;
    this.setState({ modalObj }, () => {
    });
  }

  closeModal = () => {
    let { modalObj } = this.state;
    modalObj.currIsVisible = false;
    this.setState({ modalObj });
  }

  _writeFn(value) {
    this.params.visitContent = value.replace(/(^\s*)|(\s*$)/g, "");
  }

  //打开日历选项
  _timeOpen = () => {
    this.setState({
      showTimeModal: true
    })
  }
  // 选择时间
  _resultCall = (resultData) => {
    this.dateObj.beginDate = resultData.startTime || '';
    this.dateObj.endDate = resultData.endTime || '';
    this.setState({
      showTimeModal: false
    })
  }

  _changeLog(index) {
    console.log(index)
    ImagePicker.showImagePicker(imgOptions, (response) => {
      if (response.didCancel) {
        console.log('用户取消了选择！');
      }
      else if (response.error) {
        console.log("ImagePicker发生错误：" + response.error);
      }
      else {
        source = { uri: response.uri };
        this._uploadImg(source, index);
      }
    });
  }

  async _uploadImg(imgUrl, index) {
    let uploadImgObj = {
      imgUrl,
      url: API_GENERATE(API.IMG_UPLOAD),
    }
    let responseData = await Upload.uploadImg(uploadImgObj);

    if (responseData) {
      let headObj = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId: responseData.fileId }, null, 30000);
      if (headObj) {
        this.setState({
          headImg: { uri: headObj.image }
        })
      } else {
        this.setState({
          ls: true
        })
      }
      this._changeImg(responseData.fileId, this.state.imgUrl, index);
    }
  }

  async _changeImg(fileId, imgUrl, index) {
    this.state.imgServer.splice(index, 0, source.uri);
    this.state.attachmentId.splice(index, 0, fileId);
    this.setState({
      imgServer: this.state.imgServer,
      attachmentId: this.state.attachmentId
    });
  }

  _delete(index) {
    this.state.imgServer.splice(index, 1);
    this.state.attachmentId.splice(index, 1);
    this.setState({
      imgServer: this.state.imgServer,
      attachmentId: this.state.attachmentId
    });
  }

  _checkDate() {
    const { beginDate, endDate, visitType, visitMethod, visitContent, contactorName, detailAddress } = this.params;
    if (!visitType) {
      ToastUtil.showWarning('请选择维护类型!');
      return false;
    }
    if (!visitMethod) {
      ToastUtil.showWarning('请选择维护方式!');
      return false;
    }
    if (!contactorName) {
      ToastUtil.showWarning('请选择维护对象!');
      return false;
    }
    if (!visitContent) {
      ToastUtil.showWarning('请填入维护内容!');
      return false;
    }
    if (!beginDate || !endDate) {
      ToastUtil.showWarning('请选择维护日期!');
      return false;
    }
    if (!detailAddress) {
      ToastUtil.showWarning('请选择地址!');
      return false;
    }

    return true;
  }

  _submit = async () => {
    if (this.requesting) return;
    let { addressCodeParam, choice } = this.props || {};
    let { province, city, streetName, address, poiInfo } = addressCodeParam || {};
    this.params.beginDate = CommonData._format('date2', this.dateObj.beginDate);
    this.params.endDate = CommonData._format('date2', this.dateObj.endDate);
    this.params.countryCode = '';
    this.params.provinceCode = province;
    this.params.cityCode = city;
    this.params.areaCode = streetName;
    this.params.detailAddress = address + poiInfo;
    this.params.attachmentId = this.state.attachmentId.join(',');
    this.params.corpId = choice.corpId;

    if (!this._checkDate()) return;
    this.requesting = true;
    const response = await HTTP.POST(API_GENERATE(API.ADD_STAFF_VISIT), { data: this.params });
    if (response) {
      this.requesting = false;
      ToastUtil.showSuccess('提交成功').then(() => {
        navigationSeevice.navigate('EnterpriseDetailsPage', { tabIndex: 3 });
      })
    } else {
      this.requesting = false;
    }
  }

  render() {
    let { modalObj, mainTypeText, mainMethodText, mainObjectText, showTimeModal, imgServer } = this.state;
    let { addressCodeParam } = this.props || {};
    let { province, city, streetName, address, poiInfo } = addressCodeParam || {};
    let addressText = `${province || ''}${city || ''}${streetName || ''}${poiInfo || ''}`;
    return (
      <View style={styles.createBox}>
        <View style={[styles.flexRow, styles.selectBox]}>
          <Text style={styles.needed}>*</Text>
          <TouchableOpacity
            style={[styles.flexRow, styles.select]}
            onPress={() => { this.selectMain('type') }}
          >
            <View style={styles.flexRow}>
              <Text style={styles.selectTitle}>维护类型</Text>
              <Text style={styles.selectContent}>{mainTypeText}</Text>
            </View>
            <Image source={selectIcon} style={{ tintColor: '#000' }} />
          </TouchableOpacity>
        </View>
        <View style={[styles.flexRow, styles.selectBox]}>
          <Text style={styles.needed}>*</Text>
          <TouchableOpacity
            style={[styles.flexRow, styles.select]}
            onPress={() => { this.selectMain('method') }}
          >
            <View style={styles.flexRow}>
              <Text style={styles.selectTitle}>维护方式</Text>
              <Text style={styles.selectContent}>{mainMethodText}</Text>
            </View>
            <Image source={selectIcon} style={{ tintColor: '#000' }} />
          </TouchableOpacity>
        </View>
        <View style={[styles.flexRow, styles.selectBox]}>
          <Text style={styles.needed}>*</Text>
          <TouchableOpacity
            style={[styles.flexRow, styles.select]}
            onPress={() => { this.selectMain('object') }}
          >
            <View style={styles.flexRow}>
              <Text style={styles.selectTitle}>维护对象</Text>
              <Text style={styles.selectContent}>{mainObjectText}</Text>
            </View>
            <Image source={selectIcon} style={{ tintColor: '#000' }} />
          </TouchableOpacity>
        </View>
        <View style={[styles.flexRow, styles.selectBox]}>
          <View style={{ flex: 1 }}>
            <View style={styles.flexRow}>
              <Text style={styles.needed}>*</Text>
              <Text style={styles.selectTitle}>维护内容</Text>
            </View>
            <TextInput
              style={styles.textInput}
              placeholder={'请输入本次维护内容，限定1000字。'}
              placeholderTextColor={'#B4B8C0'}
              underlineColorAndroid={'transparent'}
              onChangeText={(value) => this._writeFn(value)}
              multiline
            />
          </View>
        </View>
        <View style={[styles.flexRow, styles.selectBox]}>
          <Text style={styles.needed}>*</Text>
          <TouchableOpacity
            style={styles.flexRow}
            onPress={this._timeOpen}
          >
            <View style={styles.flexRow}>
              <Text style={styles.selectTitle}>维护日期</Text>
              <Image source={dateIcon} style={{ tintColor: '#0E7FFD', marginRight: 5, width: 14 * scale, height: 16 * scale }} />
              <View style={styles.flexRow}>
                <Text style={styles.statusItemText}>{CommonData._format('date1', this.dateObj.beginDate) || ''}</Text>
                <Text style={[styles.statusItemText, styles.statusItemTextActive]}>-</Text>
                <Text style={styles.statusItemText}>{CommonData._format('date1', this.dateObj.endDate) || ''}</Text>
              </View>
            </View>
          </TouchableOpacity>
        </View>
        <View style={[styles.flexRow, styles.selectBox]}>
          <Text style={styles.needed}>*</Text>
          <TouchableOpacity
            style={styles.flexRow}
            onPress={() => { navigationSeevice.navigate('Address', { addressCodeParam }) }}
          >
            <View style={styles.flexRow}>
              <Text style={styles.selectTitle}>地址</Text>
              <Image source={addressIcon} style={{ marginLeft: 25, marginRight: 5, width: 16, height: 22 }} />
              <Text style={[styles.selectTitle, { width: 200 * scale, flexWrap: 'wrap' }]}>{addressText || '请选择地址'}</Text>
            </View>
          </TouchableOpacity>
        </View>
        <View style={[styles.flexRow, styles.selectBox]}>
          <Text style={styles.needed}>  </Text>
          <View style={styles.flexRow}>
            <View style={styles.flexRow}>
              <Text style={[styles.selectTitle, { marginRight: 50 }]}>附件</Text>
              {
                [1, 2, 3, 4, 5].map((item, index) => {
                  return (
                    <TouchableOpacity key={index} onPress={this._changeLog.bind(this, index)}>
                      {
                        imgServer[index] ?
                          <TouchableOpacity onPress={this._delete.bind(this, index)} style={{ zIndex: 10 }}>
                            <Image style={styles.close} source={close} />
                          </TouchableOpacity> : null
                      }

                      <Image style={{ marginRight: 5, width: 30, height: 30 }}
                        source={imgServer[index] ? { uri: imgServer[index] } : defaultImg}
                      />
                    </TouchableOpacity>
                  )
                })
              }
            </View>
          </View>
        </View>

        <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
          <TouchableOpacity style={styles.button} onPress={() => this._submit()}>
            <Text style={styles.buttonText}>提交</Text>
          </TouchableOpacity>
        </View>

        {
          showTimeModal ?
            <RangTime isClear={true}
              isVisible={true}
              markedDates={null}
              startTime={this.dateObj.beginDate}
              endTime={this.dateObj.endDate}
              closeCall={() => { this.setState({ showTimeModal: false }) }}
              resultCall={this._resultCall} /> : null
        }

        <Common type="modal" demoData={(
          <Common type="listRadio"
            selectIndex={modalObj.currSelectIndex}
            title={modalObj.currTitle}
            listData={modalObj.currlistData || []}
            selectCallBack={modalObj.currCb}
          />
        )}
          isVisible={modalObj.currIsVisible}
          closeCallballFn={this.closeModal}
        />

      </View>
    )
  }
}


const styles = StyleSheet.create({
  flexRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  createBox: {
    paddingTop: 40 * scale,
    marginLeft: 30 * scale,
    marginRight: 30 * scale,
    marginBottom: 75 * scale
  },
  needed: {
    fontSize: 12 * scale,
    color: '#F80A0A',
    marginRight: 5 * scale,
  },
  selectBox: {
    marginBottom: 26 * scale,
  },
  select: {
    flex: 1,
    justifyContent: 'space-between',
    borderBottomWidth: 1,
    borderBottomColor: '#000',
    paddingBottom: 5 * scale,
  },
  selectTitle: {
    fontSize: 12 * scale,
    color: '#000000',
    marginRight: 30 * scale,
  },
  selectContent: {
    fontSize: 12 * scale,
    color: '#AAB1BF',
  },
  textInput: {
    marginTop: 6 * scale,
    height: 156 * scale,
    width: '100%',
    borderColor: '#000',
    borderWidth: 1 * scale,
    borderRadius: 4 * scale,
    padding: 12 * scale,
    paddingTop: 10 * scale,
    fontSize: 12 * scale,
  },
  statusItemText: {
    fontSize: 12 * scale,
    color: '#34475F'
  },
  button: {
    marginTop: 50 * scale,
    width: 99 * scale,
    height: 39 * scale,
    backgroundColor: '#0E7FFD',
    borderRadius: 15 * scale,
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttonText: {
    fontSize: 14 * scale,
    color: '#fff'
  },
  close: {
    position: 'absolute',
    right: 2 * scale,
    top: -4 * scale,
    width: 8 * scale,
    height: 8 * scale,
    backgroundColor: '#fff',
    zIndex: 10
  }
})